package com.jwell.bigdata.ui.web;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.*;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import com.jwell.bigdata.R;
import com.jwell.bigdata.ui.dialog.NoTitleDialog;
import com.jwell.bigdata.utils.ToastUtils;
import com.jwell.bigdata.utils.ZSUtils;

import java.io.IOException;
import java.net.HttpCookie;
import java.util.List;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by evan on 16/9/14.
 */
public class WebActivity extends AppCompatActivity {

    private String mCookieString;

    public static void startActivity(String url, String token, Activity activity) {
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("token", token);
        activity.startActivity(intent);
    }

    private static final int REQUEST_CODE = 1001;
    public static final String EXTRA_URL = "extra_url";
    public static final String EXTRA_TITLE = "extra_title";

    WebView webView;
    ProgressBar pb;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadMessageL;

    private String mUrl;
    private MWebViewClient mMWebViewClient;
    private ImageButton mIvBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_web_layout);
        initData();
        initView();
        initWebView();
    }

    private void initView() {
        webView = findViewById(R.id.webView);
        pb = findViewById(R.id.pb);
        mIvBack = findViewById(R.id.ib_back);
        mIvBack.setOnClickListener(v -> {
            onBackPressed();
        });
    }

    private void initData() {
//        mUrl = "http://47.101.60.168/tml/index#/";//生成环境
//        mUrl = "http://datav.aliyuncs.com/share/b4dd11ea045b765a1139b6ec93435818";//生成环境
        mUrl = getIntent().getStringExtra("url");
        mCookieString = getIntent().getStringExtra("token");
        System.out.println("mCookieString-1-" + mUrl + "-----" + mCookieString);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void initWebView() {

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);

        // 设置出现缩放工具
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        //扩大比例的缩放
        settings.setUseWideViewPort(true);//自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        mMWebViewClient = new MWebViewClient();
        webView.setWebChromeClient(mMWebViewClient);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                pb.setVisibility(View.VISIBLE);
                return false;
            }

            public void onPageFinished(WebView view, String url) {
                CookieManager cookieManager = CookieManager.getInstance();
                System.out.println("mCookieString-8-" +cookieManager.getCookie(url));
                if (webView.canGoBack()) {
                    mIvBack.setVisibility(View.VISIBLE);
                }
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                OkHttpClient.Builder builder;
                try {
                    builder = ZSUtils.setCertificates(new OkHttpClient.Builder(), getAssets().open("gtdn.cer"));
                } catch (IOException e) {
                    builder = new OkHttpClient.Builder();
                }
                Request request = new Request.Builder().url(view.getUrl())
                        .build();
                builder.build().newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        Dialog dialog = new NoTitleDialog.Builder(WebActivity.this)
                                .setMessage("是否忽略证书校验继续访问")
                                .setOnCancelClickListener(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        handler.cancel();
                                        finish();
                                    }
                                })
                                .setOnEnsureClickListener(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        handler.proceed();
                                    }
                                }).create();
                        if (dialog!=null){
                            dialog.show();
                        }

                    }

                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        handler.proceed();
                    }

                });
                handler.proceed();
            }
        });

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
        }

        setCookie();
        webView.loadUrl(mUrl);
    }

    protected void setCookie() {

        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();//移除

//        cookieManager.setCookie(getDomain(mUrl), "sign_in_etindustryeid_ticket="+mCookieString+";domain=47.111.65.28;path=/");
        cookieManager.setCookie("http://47.111.65.28/", "domain=47.111.65.28");
        cookieManager.setCookie("http://47.111.65.28/", "sign_in_etindustryeid_ticket="+mCookieString);
        cookieManager.setCookie("http://47.111.65.28/", "path=/cold_rolling/main_defect_pram");

        CookieSyncManager.getInstance().sync();
    }

    @Override
    protected void onResume() {
        //重新开始webview，这样做的目的是为了不让webview重复进入的时候出现无法加载url出现空白
        if (webView != null) {
            webView.onResume();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        //如果当前web服务不是null
        if (mMWebViewClient != null) {
            //通知app当前页面要隐藏它的自定义视图。
            mMWebViewClient.onHideCustomView();
        }
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //webview停止加载
        if (webView != null) {
            //webView.reload();
            webView.stopLoading();
            //webview清理内存
            webView.clearCache(true);
            //webview清理历史记录
            webView.clearHistory();
            //webview销毁
            webView.destroy();
        }
    }

    private class MWebViewClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            result.confirm();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (pb != null) {
                pb.setProgress(newProgress);
                if (newProgress == 100) {
                    pb.setVisibility(View.GONE);
                }
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadMessageL = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            WebActivity.this.startActivityForResult(Intent.createChooser(intent, "File Browser"), REQUEST_CODE);
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (mUploadMessageL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != REQUEST_CODE || mUploadMessageL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadMessageL.onReceiveValue(results);
        mUploadMessageL = null;
    }

    /**
     * 获取URL的域名
     */
    private String getDomain(String url) {
        url = url.replace("http://", "").replace("https://", "");
        if (url.contains("/")) {
            url = url.substring(0, url.indexOf('/'));
        }
        return url;
    }
}
